package start.fly.test.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import start.fly.test.database.control_user;
import start.fly.test.database.linksql;

public class register extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		control_user cu = new control_user();
		String state = request.getParameter("state");
		System.out.println("state="+state);
		if(state.equals("register")){
			String username = request.getParameter("username");
			String password1 = request.getParameter("password1");
			String password2 = request.getParameter("password2");
			String question = request.getParameter("question");
			String answer = request.getParameter("answer");
			String safecode1 = request.getParameter("safecode1");
			String safecode2 = request.getParameter("safecode2");
			//String img = request.getParameter("file");
			String email = request.getParameter("email");
			String type = request.getParameter("type");
			String shenfen;
			/*int index = img.lastIndexOf("\\");  
			  //灏嗗瓧绗︿覆杞负瀛楃鏁扮粍  
			  char[] ch = img.toCharArray();  
			  //鏍规嵁 copyValueOf(char[] data, int offset, int count) 鍙栧緱鏈�悗涓�釜瀛楃涓� 
			  String lastString = String.copyValueOf(ch, index + 1, ch.length - index - 1);
			  System.out.println("lastString="+lastString);*/
			
			if(!password1.equals(password2)){
				request.setAttribute("error1", "密码不一致");
			}else{
				System.out.println("error1");
				request.setAttribute("error1", " ");
			}
			if(!safecode1.equals(safecode2)){
				request.setAttribute("error2", "安全码不一致");
			}else{
				System.out.println("error2");
				request.setAttribute("error2", " ");
			}
			if(cu.select_user1(username)){
				request.setAttribute("warning1", "用户名已存在");
			}else {
				request.setAttribute("warning1", " ");
			}
			if(cu.select_user2(email)){
				request.setAttribute("warning2", "邮箱已存在");
			}else{
				request.setAttribute("warning2", " ");
			}
			if(!request.getAttribute("error1").equals(" ")||!request.getAttribute("error2").equals(" ")||!request.getAttribute("warning1").equals(" ")||!request.getAttribute("warning2").equals(" ")){
				System.out.println("跳转了");
				request.getRequestDispatcher("register.jsp?state=2").forward(request, response);
			}else{
				if(type.equals("1")){
					shenfen="个人用户";
				}else{
					shenfen="企业用户";
				}
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//璁剧疆鏃ユ湡鏍煎紡
				String registertime = df.format(new Date());
				cu.insert_user(username, password1, question, answer, safecode1, "0", email, shenfen,registertime);
				
				/*HttpSession session = request.getSession();
				File file ;
				   int maxFileSize = 5000 * 1024;
				   int maxMemSize = 5000 * 1024;
				   ServletContext context = this.getServletContext();
				   String filePath = context.getInitParameter("file-upload");
				   // 验证上传内容了类型
				   String contentType = request.getContentType();
				   if ((contentType.indexOf("multipart/form-data") >= 0)) {

				      DiskFileItemFactory factory = new DiskFileItemFactory();
				      // 设置内存中存储文件的最大值
				      factory.setSizeThreshold(maxMemSize);
				      // 本地存储的数据大于 maxMemSize.
				      factory.setRepository(new File("d:\\temp"));

				      // 创建一个新的文件上传处理程序
				      ServletFileUpload upload = new ServletFileUpload(factory);
				      // 设置最大上传的文件大小
				      upload.setSizeMax( maxFileSize );
				      try{ 
				         // 解析获取的文件
				         List fileItems = upload.parseRequest(request);

				         // 处理上传的文件
				         Iterator i = fileItems.iterator();

				         out.println("<html>");
				         out.println("<head>");
				         out.println("<title>JSP File upload</title>");  
				         out.println("</head>");
				         out.println("<body>");
				         while ( i.hasNext () ) 
				         {
				            FileItem fi = (FileItem)i.next();
				            if ( !fi.isFormField () )	
				            {
				            // 获取上传文件的参数
				            String fieldName = fi.getFieldName();
				            String fileName = fi.getName();
				            boolean isInMemory = fi.isInMemory();
				            long sizeInBytes = fi.getSize();
				            // 写入文件
				            if( fileName.lastIndexOf("\\") >= 0 ){
				            file = new File( filePath , 
				            fileName.substring( fileName.lastIndexOf("\\"))) ;
				            }else{
				            file = new File( filePath ,
				            fileName.substring(fileName.lastIndexOf("\\")+1)) ;
				            }
				            fi.write( file ) ;
				            out.println("Uploaded Filename: " + filePath +",filename:"+ 
				            fileName + "<br>");
				            String newfilename = fileName.substring(0,fileName.length()-4);
				            }
				         }
				         /*session.setAttribute("situation", "success");
				         response.sendRedirect("info.jsp");*/
				         /*out.println("</body>");
				         out.println("</html>");
				      }catch(Exception ex) {
				         System.out.println(ex);
				      }
				   }else{
					   /*session.setAttribute("situation", "fail");
					   response.sendRedirect("info.jsp");*/
				      /*out.println("<html>");
				      out.println("<head>");
				      out.println("<title>Servlet upload</title>");  
				      out.println("</head>");
				      out.println("<body>");
				      out.println("<p>No file uploaded</p>"); 
				      out.println("</body>");
				      out.println("</html>");
				   }*/
				
				response.sendRedirect("login.jsp");
			}
			
		}/*else if(state.equals("checkname")){
			String username = request.getParameter("username");
			System.out.println("username="+username);
			if(cu.select_user1(username)){
				request.setAttribute("warning", "用户名已存在");
			}else{
				request.setAttribute("warning", "可以继续注册");
			}
			request.getRequestDispatcher("register.jsp?state=checkname").forward(request, response);
		}*/

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
 
	}

}
